package com.neusoft.ysu.populationmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neusoft.ysu.populationmanagement.constant.Errors;
import com.neusoft.ysu.populationmanagement.constant.TabelDic;
import com.neusoft.ysu.populationmanagement.entity.CommonResult;
import com.neusoft.ysu.populationmanagement.entity.Population;
import com.neusoft.ysu.populationmanagement.mapper.PopulationMapper;
import com.neusoft.ysu.populationmanagement.service.IPopulationService;
import com.neusoft.ysu.populationmanagement.vo.TypeCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lhn
 * @since 2025-06-13
 */
@Service
public class PopulationServiceImpl implements IPopulationService {

    @Autowired
    private PopulationMapper populationMapper;
    @Autowired
    private ResPopServiceImpl resPopService;
    @Autowired
    private FloPopServiceImpl floPopService;

    /**
     * @param population
     * @return 1代表成功，2-7代表不同类型的失败
     * @author zyk
     * @date 2025-06-13
     */

    @Override
    public CommonResult checkPop(Population population) {
        LambdaQueryWrapper<Population> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Population::getIdnum, population.getIdnum()).eq(Population::getIsDelete, 0);//where idnum=输入
        List<Population> populations = populationMapper.selectList(lambdaQueryWrapper);

        if (populations.size() <= 0) {
            return new CommonResult<>(Errors.ERROR_POP_SELECT, "未查到相关身份证号人员", null);
        }
        if (!populations.get(0).getName().equals(population.getName())) {
            return new CommonResult(Errors.ERROR_POP_ID_NOT_NAME, "身份证号与姓名不符", null);
        }
        if (populations.get(0).getGenderId() != population.getGenderId()) {
            return new CommonResult<>(Errors.ERROR_POP_ID_NOT_GENDER, "身份证号与性别不符", null);
        }
        if (populations.get(0).getBloodId() != population.getBloodId()) {
            return new CommonResult<>(Errors.ERROR_POP_ID_NOT_BLOOD, "身份证号与血型不符", null);
        }
        if (!populations.get(0).getBirthday().isEqual(population.getBirthday())) {
            return new CommonResult<>(Errors.ERROR_POP_ID_NOT_BIRTHDAY, "身份证号与出生日期不符", null);
        }
        if (populations.get(0).getNationId() != population.getNationId()) {
            return new CommonResult<>(Errors.ERROR_POP_ID_NOT_NATION, "身份证号与民族不符", null);
        }
        return new CommonResult<>(1, "人员信息符合", populations.get(0));
    }

    /**
     * @param population
     * @return 1代表更新成功，101失败
     * @author zyk 赵子鉴
     * @description 更新人口基类
     * @date 2025-06-16
     * 根据身份证号进行更新
     */

    @Override
    public CommonResult updatePop(Population population) {
        //根据身份证号更新population表
        LambdaUpdateWrapper<Population> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Population::getIdnum, population.getIdnum()).eq(Population::getIsDelete, 0);
        List<Population> pops = populationMapper.selectByIdNum(population.getIdnum());
        if (pops.size() != 1) {
            return new CommonResult<>(0, "该身份证号不存在", null);
        }
        Population pop = pops.get(0);
        if (!pop.getPopTypeId().equals(population.getPopTypeId())) {
            // 变更人口类型
            Long type = chengePopType(pop, population);
            if (type == 0) {
                return new CommonResult<>(0, "人口类型更新失败", null);
            }
        }
        population.setId(pop.getId());
        int rows = populationMapper.update(population, lambdaUpdateWrapper);
        if (rows <= 0) {
            return new CommonResult<>(0, "人口数据更新失败", null);
        }
        return new CommonResult(1, "人口基本信息更新完成", population);
    }

    /**
     * @param pop_befor 数据库中数据，变化前的数据（数据类型会被改变为正确的类型）
     * @param pop_after 传入数据，变化后的数据
     * @return Long 1L-5L：变化类型，0：失败
     * @author 你自己的定义的名字
     * @description 更改人口类型函数
     * @date 2025-06-16
     */
    private Long chengePopType(Population pop_befor, Population pop_after) {

        System.out.println(pop_befor);
        System.out.println(pop_after);
        if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_RES_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_IMP_POP)) {
            // 1-2
            pop_after.setPopTypeId(TabelDic.TYPE_RES_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_RES_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_FLO_POP)) {
            // 1-3
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_POP);
            resPopService.deleteResPopByPopId(pop_befor.getId());
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_FLO_POP)) {
            // 2-3
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_FLO_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_IMP_POP)) {
            // 3-2
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_FLO_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_RES_POP)) {
            // 3-1
            pop_after.setPopTypeId(TabelDic.TYPE_RES_POP);
            floPopService.deleteFloPopByPopId(pop_befor.getId());
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_RES_POP)) {
            // 2-1
            pop_after.setPopTypeId(TabelDic.TYPE_RES_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_RES_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_RES_POP)) {
            // 4-1
            pop_after.setPopTypeId(TabelDic.TYPE_RES_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_RES_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_IMP_POP)) {
            // 4-2
            pop_after.setPopTypeId(TabelDic.TYPE_RES_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_RES_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_FLO_POP)) {
            // 4-3
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_IMP_POP);
            resPopService.deleteResPopByPopId(pop_befor.getId());
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_FLO_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_RES_POP)) {
            // 5-1
            pop_after.setPopTypeId(TabelDic.TYPE_RES_IMP_POP);
            floPopService.deleteFloPopByPopId(pop_befor.getId());
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_FLO_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_IMP_POP)) {
            // 5-2
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_IMP_POP);
        } else if (pop_befor.getPopTypeId().equals(TabelDic.TYPE_FLO_IMP_POP) && pop_after.getPopTypeId().equals(TabelDic.TYPE_FLO_POP)) {
            // 5-3
            pop_after.setPopTypeId(TabelDic.TYPE_FLO_IMP_POP);
        }

        return pop_after.getPopTypeId();
    }

    @Override
    public CommonResult insertPop(Population population) {
        population.setCreateTime(LocalDateTime.now());
        population.setIsDelete(TabelDic.IS_DELETE_NO);
        if (populationMapper.selectByIdNum(population.getIdnum()).size() != 0) {
            return new CommonResult<>(0, "该身份证号已存在", null);
        }
        population.setId(null);
        int rows = populationMapper.insert(population);
        if (rows <= 0) {
            return new CommonResult<>(0, "人口基本信息插入失败", null);
        }

        return new CommonResult<>(1, "新增常住人口成功", population);
    }

    @Override
    public CommonResult deletePop(Population population) {
        List<Population> pops = populationMapper.selectByIdNum(population.getIdnum());
        if (pops.size() == 1) {
            pops.get(0).setIsDelete(1);
            int rows = populationMapper.update(pops.get(0), new LambdaUpdateWrapper<Population>().eq(Population::getId, pops.get(0).getId()));
            return new CommonResult<>(1, "删除成功", pops.get(0));
        }
        return new CommonResult<>(0, "删除失败", null);
    }

    @Override
    public CommonResult selectByAddress(String area) {
        List<TypeCount> typeList=populationMapper.selectByAddress(area);
        Map<Integer,Integer> typeMap = new HashMap<>();
        for (TypeCount typeCount:
             typeList) {
            typeMap.put(typeCount.getPopTypeId(),typeCount.getPopCount());
        }
        return new CommonResult<>(1, "查询成功",typeMap);
    }

    @Override
    public CommonResult selectByIdNum(String idnum) {
        List<Population> pops = populationMapper.selectByIdNum(idnum);
        if (pops.size() != 1) {
            return new CommonResult(0, "该身份证号不存在或不唯一", null);
        }
        return new CommonResult(1, "身份证号查询成功", pops.get(0));
    }

    @Override
    public CommonResult queryByAddress(String area) {
        List<Population> popList=populationMapper.queryByAddress(area);
        return new CommonResult<>(1,"查询成功",popList);
    }

}
